<template>
    <div class="white-box">
        <div>
            <el-button
                v-hasPermi="['enttp:role:add']"
                class="table-mb"
                type="primary"
                @click="onClickAdd"
                >添加角色</el-button
            >
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">角色名称：</span>
                <el-input
                    placeholder="请输入角色名称"
                    v-model.trim="state.roleName"
                    clearable
                    @keyup.enter.native="handleSearch"
                ></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">权限字符：</span>
                <el-input
                    placeholder="请输入权限字符"
                    v-model.trim="state.roleKey"
                    clearable
                    @keyup.enter.native="handleSearch"
                ></el-input>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:role:del']"
                @click="onClickDel()"
                >批量删除角色</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                type="selection"
                width="55"
                v-hasPermi="['enttp:role:del']"
                :selectable="(row) => row.deletable === 0"
            />
            <el-table-column
                prop="roleName"
                label="角色名称"
                min-width="250"
                fixed="left"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                prop="roleKey"
                label="权限字符"
                min-width="150"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                prop="level"
                label="等级"
                min-width="100"
                sortable="custom"
            ></el-table-column>
            <el-table-column label="数据范围" min-width="150">
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName("data_scope", row.dataScope)
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("data_status", row.status) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickDetails(row.sid),
                                    'v-hasPermi': ['enttp:role:query'],
                                },
                                text: '详情',
                            },
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                    'v-hasPermi': ['enttp:role:edit'],
                                },
                                text: '修改',
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:role:del'],
                                },
                                text: '删除',
                                isRender: row.deletable === 0,
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-drawer v-model="state.showDetail" title="角色详情" size="540">
        <template v-if="detail">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="7" align="end">角色名称</el-col>
                <el-col :span="17">{{ detail.roleName }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20">权限字符</el-col>
                <el-col :span="17">{{ detail.roleKey }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20">角色等级</el-col>
                <el-col :span="17">{{ detail.level }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20">数据范围</el-col>
                <el-col :span="17">{{
                    dictStore.getDictMemberName("data_scope", detail.dataScope)
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20"
                    >绑定的后台菜单</el-col
                >
                <el-col :span="17"
                    ><el-tree
                        ref="menusRef"
                        :data="state.menus"
                        node-key="sid"
                        class="mt--3 mb-10"
                        :props="defaultProps"
                        :filter-node-method="filterMenus"
                        empty-text=""
                    />
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20"
                    >绑定的小程序菜单</el-col
                >
                <el-col :span="17">
                    <el-tree
                        ref="miniMenusRef"
                        :data="state.miniMenus"
                        node-key="sid"
                        class="mt--3 mb-10"
                        :props="defaultProps"
                        :filter-node-method="filterMiniMenus"
                        empty-text=""
                    />
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20">状态</el-col>
                <el-col :span="17">{{
                    dictStore.getDictMemberName("data_status", detail.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20">备注</el-col>
                <el-col :span="17">{{ detail.note }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20">是否可删除</el-col>
                <el-col :span="17">{{
                    dictStore.getDictMemberName("deletable", detail.deletable)
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7" align="end" class="mb-20">创建时间</el-col>
                <el-col :span="17">{{ detail.created }}</el-col>
            </el-row>
        </template>
    </el-drawer>
</template>

<script setup>
import {
    inject,
    reactive,
    onMounted,
    onActivated,
    toRefs,
    ref,
    nextTick,
} from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import { getRoles, delRoles, getRoleDetail } from "@/apis/system/role";
import { getMenusTree, getMiniMenusTree } from "@/apis/system/menu.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status");
dictStore.getDictMembers("data_scope");
dictStore.getDictMembers("deletable");

const $message = inject("$message");
const router = useRouter();

const menusRef = ref(null);
const miniMenusRef = ref(null);
const state = reactive({
    ascended: false,
    roleKey: null,
    roleName: null,
    sortFieldName: null,
    sidList: [],
    showDetail: false,
    detail: null,
    menus: [],
    selectedMenus: [],
    miniMenus: [],
    selectedMiniMenus: [],
});
const defaultProps = {
    label: "menuName",
};
const { detail } = toRefs(state);

onActivated(() => {
    pubParams(getList);
    getMenus();
    getMiniMenus();
});

const getMenus = async () => {
    const res = await getMenusTree();
    if (res.data.code == 200) {
        state.menus = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getMiniMenus = async () => {
    const res = await getMiniMenusTree();
    if (res.data.code == 200) {
        state.miniMenus = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const filterMenus = (_, data) => {
    return state.detail?.menuSids?.includes(data.sid);
};

const filterMiniMenus = (_, data) => {
    return state.detail?.programsMenuSids?.includes(data.sid);
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    getdata,
    page,
    pageSizeNum,
    pageSize,
    totalNums,
    pubParams,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getRoles({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            roleKey: state.roleKey,
            roleName: state.roleName,
            sortFieldName: state.sortFieldName,
        })
    );
}

/**
 * 搜索
 * @param {Function} handleSearch 搜索
 */

const handleSearch = () => {
    pubRefreshParams(getList);
};

/**
 * 点击添加菜单
 * @param {Function} onClickAdd 跳转到新增页
 */
const onClickAdd = () => {
    router.push({ name: "RoleAdd" });
};

/**
 * 排序
 * @param {Function} sortChange 排序
 */
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

/**
 * 点击修改按钮
 * @param {Function} onClickEdit 跳转修改页
 */
const onClickEdit = (sid) => {
    sid &&
        router.push({
            name: "RoleEdit",
            query: {
                sid,
            },
        });
};

// 跳转详情
const onClickDetails = async (sid) => {
    state.showDetail = true;
    state.detail = null;
    await getDetails(sid);
    nextTick(() => {
        menusRef.value.filter();
        miniMenusRef.value.filter();
    });
};

const getDetails = async (sid) => {
    const res = await getRoleDetail({ sid });
    if (res.data.code == 200) {
        state.detail = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};
/**
 * 点击删除按钮
 * @param {Function} onClickDel 删除菜单
 */
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除角色吗？");
    const res = await delRoles({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};
</script>

<style lang="less" scoped>
:deep(.el-tree__empty-block) {
    min-height: auto;
}
</style>
